package com.wefans.wefansapp.activity;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.BenefitResultData;
import com.wefans.wefansapp.common.tool.data.BenefitResultResponseData;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetImage;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.preference.MFSharedPreference;

public class BenefitResultActivity extends BaseActivity implements OnItemClickListener, IOnNetworkListener  {

	private BenefitResultData mBenefitResultItems = new BenefitResultData();
	private ArrayList<BenefitResultResponseData> mBenefitResultResponse = new ArrayList<BenefitResultResponseData>();
	private BenefitResultAdaptor mBenefitResultAdapter = null;
	private ListView mLvBenefitResult = null;
    private DrawerLayout   m_DrawerLayout  = null;
    private FrameLayout    m_DrawerView    = null;
    private MFNetworkManager m_oNetworManager = null;
    private MFDataManager    m_oDataManager   = null;
    private MFSharedPreference msp = null;
    private Intent it;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		setContentView(R.layout.activity_benefit_result);
		
		initialize();
        installEvent();
		setTitle("BenefitResult");
		msp = new MFSharedPreference(this);
		mLvBenefitResult = (ListView) findViewById(R.id.LV_BENEFIT_RESULT);
		String bkColor = new String("#FEF2DC");
		mLvBenefitResult.setBackgroundColor(Color.parseColor(bkColor));
				
		//mBenefitResultItems = BenefitResultData>();

		
	}
	
	@Override
    protected void onPause()
    {
        MFDebug.d(">> onPause()");
        
        notifyDoClaseDrawerMenu();
        
        super.onPause();
    }
    
    @Override
    protected void notifyDoClaseDrawerMenu()
    {
        MFDebug.d(">> notifyDoClaseDrawerMenu()");
        
        super.notifyDoClaseDrawerMenu();
        
        if( m_DrawerLayout == null ) {
            MFDebug.e(new Exception("There are NO Drawer-Layout"));
            return;
        }
        
        if( m_DrawerView == null ) {
            MFDebug.e(new Exception("There are NO Drawer-View"));
            return;
        }
        
        m_DrawerLayout.closeDrawer(m_DrawerView);
        m_sdQuickMenu.close();
    }
	

	@Override
	public void onItemClick(AdapterView<?> context, View v, int position, long id) {
		//todo position정보에 따른 파라미터 셋팅 필요
		//회원키, 인덱스
		it = new Intent(getApplicationContext(), BenefitUserActivity.class);
		it.putExtra("event_idx", String.valueOf(mBenefitResultResponse.get(position).getIdx()));
		startActivity(it);
	}
	
	@Override
    public void onClick(View v)
    {
        MFDebug.d(">> onClick()");
        
        switch( v.getId() ) {
            case R.id.IB_BENEFIT_RESULT_HEADER_LEFT_BUTTON :
                m_DrawerLayout.openDrawer(m_DrawerView);
                break;
            default :
                break;
        }
        
        super.onClick(v);
    }
	
    private void initialize()
    {
        MFDebug.d(">> initialize()");
        
        m_oNetworManager = MFNetworkManager.getInstance(this);
        m_oDataManager   = MFDataManager.getInstance(this);
        
        //아래 member정보에 투입(null체크필요)  msp.getMem_idx()
        RequestServerBenefitResultData("42750");
        //Contents layout adding
        FrameLayout containerContents = (FrameLayout) findViewById(R.id.FL_BENEFIT_RESULT_CONTAINER);
        addContentsLayout(containerContents, R.layout.layout_benefit_result);
        addQuickMenuLayout(containerContents);
        
        //Drawer menu adding
        m_DrawerView = (FrameLayout) findViewById(R.id.FL_BENEFIT_RESULT_DRAWER_LAYOUT);
        addDrawerLayout(m_DrawerView);
        
        //set drawer layout (root)
        m_DrawerLayout = (DrawerLayout) findViewById(R.id.DL_BENEFIT_RESULT_NAVIGATION_LAYOUT);
    }
    
    private void installEvent()
    {
        MFDebug.d(">> installEvent()");
   
        ((ImageButton) findViewById(R.id.IB_BENEFIT_RESULT_HEADER_LEFT_BUTTON)).setOnClickListener(this);
        
    }

	private void RequestServerBenefitResultData(String mem_idx){
		 m_oNetworManager.requestBenfitResult(mem_idx, this);	
	}
    
	@Override
	public void onNetMessage(int resultCode, NetMessage message) {
	    MFDebug.d(">> onNetMessage()");
	    MFDebug.d("++ resultCode : " + resultCode);
	    MFDebug.d("++ message : " + message);
	    
	    try {
	        //서버 여동 데이터
	        if( message instanceof NetJsonData ) {
	            long magicNum = ((NetJsonData) message).getMagicNum();
	            String json = ((NetJsonData) message).getResponseJson();
	            
	            if( json == null ) {
	                throw new Exception("invalid json data");
	            }
	            
	            Gson gson = new Gson();
	            
	            if( magicNum == MFNetworkManager.REQUEST_BENEFIT_RESULT ) {
	            	mBenefitResultItems = (BenefitResultData)gson.fromJson(json, BenefitResultData.class);
	                if( mBenefitResultItems == null ) {
	                    throw new Exception("Gson parsing error");
	                }
	                m_oDataManager.setBenefitResultData(mBenefitResultItems);
	                mBenefitResultResponse = (ArrayList<BenefitResultResponseData>) mBenefitResultItems.getData().clone();
	        		mBenefitResultAdapter = new BenefitResultAdaptor(this, R.layout.list_item_benefit_result, mBenefitResultResponse);
	        		mBenefitResultAdapter.notifyDataSetChanged();
	        		mLvBenefitResult.setAdapter(mBenefitResultAdapter);
	        		mLvBenefitResult.setOnItemClickListener(this);
	                
	            } 
	        }
	        //이미지 데이터
	        else if( message instanceof NetImage ) {
	            
	        }
	        else {
	            //ignore...
	        }
	    } catch(Exception e) {
	        MFDebug.e(e);
	    }
	}
	
	private class BenefitResultAdaptor extends ArrayAdapter<BenefitResultResponseData> {

		private Context                                m_ctx         = null;                           
	    private int                                    m_nResID      = -1;
	    private ArrayList<BenefitResultResponseData>      m_alsItems    = null;
	    private LayoutInflater                         m_inflater    = null;
	    
	    
		public BenefitResultAdaptor(Context ctx, int nResID, ArrayList<BenefitResultResponseData> aylsItems) {
	        super(ctx, nResID, aylsItems);
	        MFDebug.d(">> NMHistoryAdapter::NMNoticeAdapter(ctx, nResID, aylsItems) ");
	        this.m_ctx       = ctx;
	        this.m_nResID    = nResID;
	        this.m_alsItems  = aylsItems;
	        this.m_inflater  = (LayoutInflater)m_ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    }
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			MFDebug.d(">> Benefit::getView()");
			MFDebug.d("++ position=" + position);
			MFDebug.d("++ convertView=" + convertView);
	        MFDebug.d("++ parent=" + parent);

	        final BenefitResultResponseData dBenefitResultResponse = m_alsItems.get(position);

	        ViewHolder vh = null;
	        
			if (convertView == null) {
				convertView = m_inflater.inflate(m_nResID, null);
				vh = new ViewHolder();
				vh.ivBenfitResultImage 	= (ImageView) convertView.findViewById(R.id.IV_BENEFIT_RESULT_LIST_IMG);
				vh.tvDescription1 	= (TextView) convertView.findViewById(R.id.TV_BENEFIT_RESULT1);
				vh.tvDescription2 	= (TextView) convertView.findViewById(R.id.TV_BENEFIT_RESULT2);
				//vh.tvUserBtn 	    = (TextView) convertView.findViewById(R.id.TV_BENEFIT_USER_CONFIRM);
				convertView.setTag(vh);
			}
	        else
	        {
	            vh = (ViewHolder) convertView.getTag();
	        }
			
			vh.ivBenfitResultImage.setImageDrawable(LoadImageFromWebURL(dBenefitResultResponse.getImg_url()));
			vh.tvDescription1.setText(dBenefitResultResponse.getTitle());
			vh.tvDescription2.setText(dBenefitResultResponse.getStart_date()+"~"+ dBenefitResultResponse.getEnd_date());
			//vh.tvUserBtn.setText(this.getContext().getString(R.string.benfit_confirm_user));
			
	        return convertView;
	    }
		
		private Drawable LoadImageFromWebURL(String url){
			try{
				InputStream is = (InputStream) new URL(url).getContent();
				Drawable d = Drawable.createFromStream(is,"src name");
				return d;
			}catch (Exception e){
				MFDebug.d(">> LoadImageFromWebURL() error: " + e);
				return null;
			}
		}
		
	    public class ViewHolder
	    {
	    	ImageView ivBenfitResultImage 	= null;
	        TextView  tvDescription1  	= null;
	        TextView  tvDescription2 			= null;
	        //TextView  tvUserBtn		    = null;
	    }
	}

}